import {
  getToken
} from '@/utils/token'
import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login'
// import Layout from '@/views/Layout'
// import Home from '@/views/Home'
// import User from '@/views/User'
// import Search from '@/views/Search'
// import SearchResult from '@/views/Search/SearchResult'
// import ArticleDetail from '@/views/ArticleDetail'
// import UserEdit from '@/views/User/UserEdit'
// import Chat from '@/views/Chat'

//总结
//路由懒加载：为了让第一个页面，加载的app.js小一点，打开网页快一点
//思路：把组件对应js，分成若干个.js，路由切换到哪个页面，才去加载对应的.js文件
//原因：webpack分析入口时，发现router里上来就import所有页面，所以直接打包进app.js -> 很大
//解决：当路由路径匹配规则时，才去import引入对应的组件js文件

Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/layout/home'
}, {
  path: '/login',
  component: () => import( /*webpackChunkName:"Login"*/ '@/views/Login'),
  //路由独享守卫
  // beforeEnter(to, from, next) {
  //   if (!!getToken() && to.path == '/login') {
  //     next('/layout/home')
  //   } else {
  //     next()
  //   }
  // }
}, {
  path: '/layout',
  component: () => import( /*webpackChunkName:"Layout"*/ '@/views/Layout'),
  children: [{
      path: 'home',
      component: () => import( /*webpackChunkName:"Home"*/ '@/views/Home'),
      meta: {
        scrollT: 0
      }
    },
    {
      path: 'user',
      component: () => import( /*webpackChunkName:"User"*/ '@/views/User')
    }
  ]
}, {
  path: '/search',
  component: () => import( /*webpackChunkName:"Search"*/ '@/views/Search')
}, {
  //搜索结果
  path: '/search_result/:kw',
  component: () => import( /*webpackChunkName:"SearchResult"*/ '@/views/Search/SearchResult')
}, {
  //文章详情
  path: '/detail',
  component: () => import( /*webpackChunkName:"ArticleDetail"*/ '@/views/ArticleDetail')
}, {
  path: '/user_edit',
  component: () => import( /*webpackChunkName:"UserEdit"*/ '@/views/User/UserEdit')
}, {
  path: '/chat',
  component: () => import( /*webpackChunkName:"Chat"*/ '@/views/Chat')
}]

const router = new VueRouter({
  routes
})

//路由 - 全局前置守卫（在路由发生真正跳转之前，执行此函数）
//此函数可以决定路由是否跳转/取消/强制中断切换到别的路由
router.beforeEach((to, from, next) => {
  //需求：如果已经登录了，不要切换到登录页面
  if (!!getToken() && to.path == '/login') {
    // next(false)
    next('/layout/home')
  } else {
    next()
  }
})

export default router
